import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: '/api', // url = base url + request url
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {

    if (store.getters.token) {
      // config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  async (response) => {
    console.log('request',response.data)
    if (response.data.success){
      return  response.data
    }else if(response.data.code===500){
      await store.dispatch('user/logout')
      Message({
        message: response.data.msg,
        type: 'error',
        duration: 5 * 1000
      })
    }
    else {
      Message({
        message: '请求有误',
        type: 'error',
        duration: 5 * 1000
      })
      await store.dispatch('user/logout')
      return Promise.reject()
    }

  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
